<?php
namespace app\beautiful\controller\admin\mall;
use app\BaseController;
use app\common\logic\DataLogic;
use app\beautiful\model\mall\GoodsCategoryModel;
use app\beautiful\model\mall\GoodsModel;
use app\beautiful\model\mall\GoodsSkuModel;

class Goods extends BaseController{
    protected $name='商品';
    public function index()
    {
        $name=$this->request->param('name');
        $bg_take_count=$this->request->param('bg_take_count/d');
        $end_take_count=$this->request->param('end_take_count/d');
        $status=$this->request->param('status/d',1);
        $where=[
            ['shop_id','=',$this->request->shopId],
            ['is_delete','=',0],
        ];
        if(!empty($name)) $where[]=['name','=',$name];

        if(!empty($bg_take_count)){
            if(!empty($end_take_count)){
                $where[]=['take_count','between',[$bg_take_count,$end_take_count]];
            }else{
                $where[]=['take_count','>=',$bg_take_count];
            }
        }else{
            if(!empty($end_take_count)){
                $where[]=['take_count','<=',$end_take_count];
            }
        }

        if(in_array($status,[1,3])) $where[]=['quota','>',0];
        if($status==1) $where[]=['status','=',1];
        if($status==2) $where[]=['quota','<=',0];
        if($status==3) $where[]=['status','=',-1];

        $goods_model= new GoodsModel();
        $order=['sort'=>'desc','update_time'=>'desc','goods_id'=>'desc'];
        $field="*";
        $append=['add_time_format'];
        $return = DataLogic::getDataList($goods_model,$where,$order,$field,$this->request->limit,$this->request->page,$append);
        return $this->success($return);
    }

    public function show()
    {
        $category=$this->getCategoryTreeData(0);

        $goods_id=$this->request->param('goods_id/d',0);
        if($goods_id==0) return $this->success(['category'=>$category]);

        if(null === $goods= GoodsModel::find($goods_id)) return $this->error($this->name.'不存在');
        if($goods->is_delete!=0) return $this->error($this->name.'不存在');
        if($goods->shop_id != $this->request->shopId) return $this->error($this->name.'不存在');

        $sku=GoodsSkuModel::where([['goods_id','=',$goods_id],['is_delete','=',0]])->select()->toArray() ?? [];
        $detail=[
            'name'=>$goods->name,
            'code'=>$goods->code,
            'category_id'=>$goods->category_id,
            'sort'=>$goods->sort,
            'original_price'=>$goods->original_price,
            'vip_price'=>$goods->vip_price,
            'quota'=>$goods->quota,
            'fictitious_take_count'=>$goods->fictitious_take_count,
            'is_tui'=>$goods->is_tui,
            'is_open_yu'=>$goods->is_open_yu,
            'yu_price'=>$goods->yu_price,
            'yu_days'=>$goods->yu_days,
            'is_have_sku'=>$goods->is_have_sku,
            'sku'=>$sku,
            'cover_img'=>$goods->cover_img,
            'rotation'=>$goods->rotation,
            'goods_details'=>$goods->goods_details,
            'purchase_information'=>$goods->purchase_information,
        ];
        return $this->success(['category'=>$category,'detail'=>$detail]);
    }

    protected function getCategoryTreeData($pid=0)
    {
        $return=[];
        $category= GoodsCategoryModel::where([
            ['shop_id','=',$this->request->shopId],
            ['is_delete','=',0],
            ['pid','=',$pid]
        ])->select()->toArray();
        if(!empty($category)){
            foreach ($category as $k => $v){
                $return[$k]=[
                    'title'=>$v['name'],
                    'value'=>$v['category_id'],
                    'key'=>$v['category_id'],
                    'children'=> $this->getCategoryTreeData($v['category_id']),
                ];
            }
        }
        return $return;
    }

    public function save()
    {
        $goods_id = $this->request->param('goods_id/d',0);
        $name=$this->request->param('name');
        $code=$this->request->param('code');
        $category_id=$this->request->param('category_id/d',0);
        $sort=$this->request->param('sort/d',0);
        $original_price=$this->request->param('original_price/f',0);
        $vip_price=$this->request->param('vip_price/f',0);
        $quota=$this->request->param('quota/d',0);
        $fictitious_take_count=$this->request->param('fictitious_take_count/d',0);
        $is_tui=$this->request->param('is_tui/d',0);
        $is_open_yu=$this->request->param('is_open_yu/d',0);
        $yu_price=$this->request->param('yu_price/f',0);
        $yu_days=$this->request->param('yu_days/d',0);
        $is_have_sku=$this->request->param('is_have_sku/d',0);
        $sku=$this->request->param('sku','','security_json_or_array');
        $cover_img=$this->request->param('cover_img');
        $rotation=$this->request->param('rotation/a',[]);
        $goods_details=$this->request->param('goods_details','','security_json_or_array');
        $purchase_information=$this->request->param('purchase_information');

        //判断传来的参数
        if(empty($name)) return $this->error('请输入名称');
        if(empty($code)) return $this->error('请输入编码');
        if(empty($category_id)) return $this->error('请选择分类');
        if(empty($sort)) return $this->error('请输入排序');
        if(empty($original_price) || $original_price<=0) return $this->error('请输入原价，且不能小于0');
        if(empty($vip_price) || $vip_price <= 0) return $this->error('请输入会员价，且不能小于0');
        if($vip_price>$original_price) return $this->error('会员价不能大于原价');
        if((empty($quota) || $quota<=0) && $is_have_sku==0) return $this->error('请输入配额，且不能小于0');
        //if(empty($fictitious_take_count) || $fictitious_take_count <=0) return $this->error('请输入需要展示的销量');
        if(!in_array($is_tui,[0,1])) return $this->error('未设置是否推荐');
        if(!in_array($is_open_yu,[0,1])) return $this->error('未设置是否开启预售');
        if($is_open_yu==1){
            if(empty($yu_price) || $yu_price<=0) return $this->error('请输入预售价格，且不能小于0');
            if(empty($yu_days) || $yu_days <= 0) return $this->error('请输入预售支付后几天发货');
        }
        if(!in_array($is_have_sku,[0,1])) return $this->error('未设置是否有规格');
        if($is_have_sku==1){
            $quota=0;
            if(empty($sku) || !is_array($sku)) return $this->error('请填写规格');
            foreach ($sku as $k => $v){
                if(empty($v['name'])) return $this->error('请输入规格第'.($k+1).'行的名称');
                if(empty($v['original_price']) || $v['original_price'] <= 0) return $this->error('请输入规格第'.($k+1).'行的原价，且不能小于0');
                if(empty($v['vip_price']) || $v['vip_price'] <= 0) return $this->error('请输入规格第'.($k+1).'行的会员价，且不能小于0');
                if($v['vip_price'] > $v['original_price']) return $this->error('规格第'.($k+1).'行的会员价不能大于原价');
                if($is_open_yu==1){
                    if(empty($v['yu_price']) || $v['yu_price'] <= 0) return $this->error('请输入规格第'.($k+1).'行的预售价，且不能小于0');
                    if($v['yu_price'] > $v['vip_price']) return $this->error('规格第'.($k+1).'行的预售价不能大于会员价');
                }
                if(empty($v['quota']) || $v['quota'] <= 0) return $this->error('请输入规格第'.($k+1).'行的配额，且不能小于0');
                $quota=$quota+$v['quota'];
             }
        }
        if(empty($cover_img)) return $this->error('请上传缩略图');
        if(empty($rotation) || !is_array($rotation) || count($rotation)>5) return $this->error('请上传轮播图，且数量不能多余5个');
        if(empty($goods_details)) return $this->error('请填写商品详情');
        if(empty($purchase_information)) return $this->error('请输入购买须知');

        //保存操作
        if($goods_id != 0){
            if(null === $goods= GoodsModel::find($goods_id)) return $this->error($this->name.'不存在');
            if($goods->is_delete!=0) return $this->error($this->name.'不存在');
            if($goods->shop_id != $this->request->shopId) return $this->error($this->name.'不存在');
            $pre_cover_img=$goods->cover_img; $pre_rotation=$goods->rotation; $pre_goods_details=$goods->goods_details;
        }else{
            $goods = new GoodsModel();
            $goods->shop_id = $this->request->shopId;
            $pre_cover_img=null; $pre_rotation=[]; $pre_goods_details=[];
        }
        $goods->name=$name;
        $goods->code=$code;
        $goods->category_id=$category_id;
        $goods->sort=$sort;
        $goods->original_price=$original_price;
        $goods->vip_price=$vip_price;
        $goods->quota=$quota;
        $goods->fictitious_take_count=$fictitious_take_count;
        $goods->is_tui=$is_tui;
        $goods->is_open_yu=$is_open_yu;
        if($is_open_yu==1){
            $goods->yu_price=$yu_price;
            $goods->yu_days=$yu_days;
        }
        $goods->is_have_sku=$is_have_sku;
        $goods->cover_img=$cover_img;
        $goods->rotation=$rotation;
        $goods->goods_details=$goods_details;
        $goods->purchase_information=$purchase_information;
        $goods->update_time=$this->request->time();
        $goods->status=1;
        $goods->save();

        //规格操作
       if($is_have_sku==1){
           $old_sku=GoodsSkuModel::where([
               ['shop_id','=',$this->request->shopId],
               ['goods_id','=',$goods->goods_id],
               ['is_delete','=',0]
           ])->select()->toArray();
           $update_goods_ids=array_column($sku,'sku_id') ?? []; $delete_goods_sku=[];
           $old_sku_ids=array_column($old_sku,'sku_id') ?? [];
           foreach ($old_sku as $k => $v){
               if(!in_array($v['sku_id'],$update_goods_ids)){
                   $v['is_delete']=1;
                   $delete_goods_sku[]=$v;
               }
           }

           foreach ($sku as $k => $v){
               $sku[$k]['shop_id']=$this->request->shopId;
               $sku[$k]['goods_id']=$goods->goods_id;
               if(isset($v['sku_id'])){
                   if(!in_array($v['sku_id'],$old_sku_ids)) unset($sku[$k]);
               }
           }
           $new_sku=array_merge($sku,$delete_goods_sku);
           //删除
           $goods_sku_model= new GoodsSkuModel();
           $goods_sku_model->saveAll($new_sku);
       }

        //图片操作
        imgReplaceAct($cover_img,$pre_cover_img);
        arrayNoUseImg($pre_rotation); arrayUseImg($rotation);
        arrayNoUseImg($pre_goods_details); arrayUseImg($goods_details);
        return $this->success('操作成功');
    }


    public function undercarriage()
    {
       $goods_id=$this->request->param('goods_id/d',0);

        if(null === $goods= GoodsModel::find($goods_id)) return $this->error($this->name.'不存在');
        if($goods->is_delete!=0) return $this->error($this->name.'不存在');
        if($goods->shop_id != $this->request->shopId) return $this->error($this->name.'不存在');
        if($goods->status == -1) return $this->error($this->name.'已下架');
        //其他判断后面补充

        $goods->status=-1;
        $goods->save();
        return $this->success('下架成功');
    }

    public function grounding()
    {
        $goods_id=$this->request->param('goods_id/d',0);

        if(null === $goods= GoodsModel::find($goods_id)) return $this->error($this->name.'不存在');
        if($goods->is_delete!=0) return $this->error($this->name.'不存在');
        if($goods->shop_id != $this->request->shopId) return $this->error($this->name.'不存在');
        if($goods->status == 1) return $this->error($this->name.'已上架');
        //其他判断后面补充

        $goods->status=1;
        $goods->update_time=$this->request->time();
        $goods->save();
        return $this->success('下架成功');
    }

    public function choose()
    {
        $name=$this->request->param('name');
        $type=$this->request->param('type','flash_sale');
        $goods_id=$this->request->param('goods_id/d',0);
        $where=[
            ['shop_id','=',$this->request->shopId],
            ['is_delete','=',0],
            ['is_open_yu','=',0],
            ['status','=',1],
            ['quota','>',0]
        ];
        if(!empty($name)) $where[]=['name','=',$name];
        if($goods_id != 0) $where[]=['goods_id','<>',$goods_id];
        $goods_model= new GoodsModel();
        $goods_model = $goods_model->with(['sku'=>function($query){
            $query->where([
                ['shop_id','=',$this->request->shopId],
                ['is_delete','=',0]
            ]);
        }]);
        $order=['sort'=>'desc','update_time'=>'desc','goods_id'=>'desc'];
        $append=['add_time_format'];
        $field="*";
        $return = DataLogic::getDataList($goods_model,$where,$order,$field,$this->request->limit,$this->request->page,$append);
        return $this->success($return);
    }
}
